package com.fc.h5dispaly.h5display.ggBook.socket.messenger;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import com.fc.h5dispaly.h5display.R;

import static com.fc.h5dispaly.h5display.ggBook.socket.messenger.MessengerService.MSG_FROM_CLIENT;


public class MessengerActivity extends Activity {
    private static final String TAG = "MessengerActivity";
    public static final int MSG_FROM_SERVICE = 1;
    private Messenger mService;
    private Messenger mGetReplyMessenger = new Messenger(new MessengerHandler());

    private static class MessengerHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_FROM_SERVICE:
                    Log.i(TAG, "receive msg from Service:" + msg.getData().getString("reply"));
                    break;
                default:
                    super.handleMessage(msg);
            }
            super.handleMessage(msg);
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d(TAG, "bind service  onServiceConnected");
            mService = new Messenger(iBinder);
            Message msg = Message.obtain(null, MSG_FROM_CLIENT);
            Bundle bundle = new Bundle();
            bundle.putString("msg", "你好，我是客户端");
            msg.setData(bundle);
            // 客户端发送消息的时候需要把客户端接收服务端的消息的Messenger  通过Message的replyTo传递给服务端
            msg.replyTo = mGetReplyMessenger;

            try {
                mService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.messenger_activity_main);
        Intent intent = new Intent(this,MessengerService.class);
        boolean b =  bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        Log.i(TAG, "onCreate bindService  "+b);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mConnection);
    }
}
